package com.webserver.http;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 保存所有和HTTP协议有关的定义
 */
public class HttpContext {
    /*
       资源后缀与Content-Type头的对应关系
       key:资源后缀名     value:Content-Type对应的值
    */
    private static Map<String,String> mimeMapping = new HashMap<>();

    static {
        initMimeMapping();//初始化mimeMapping
    }

    private static void initMimeMapping(){

        System.out.println(mimeMapping.size());
    }

    public static void main(String[] args) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read("./web.xml");
            Element root = doc.getRootElement();
            List<Element> list = root.elements("mime-mapping");
            for (Element mimeEle : list){
                String key = mimeEle.getText();
                String value = mimeEle.getText();
                mimeMapping.put(key,value);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        String type = getMimeType("mp3");
        System.out.println(type);
    }
    /**
     * 根据资源后缀获取对应的Content-Type值
     * @param ext
     * @return
     */
//    public static String getMimeType(String ext){
//        return mimeMapping.get(ext);
//    }
    public static String getMimeType(String ext){
        return mimeMapping.get(ext);
    }

}
